<template>
	<view class="picGroup">
		<view :style="{width: width+'px', aspectRatio: ratio}" class="box add" v-if="!formData.tmpurl"
			@click="selectPicurl">
			<uni-icons type="plusempty" size="30" color="#999"></uni-icons>
		</view>
		<view :style="{width: width+'px', aspectRatio: ratio}" class="box pic" v-else>
			<image :src="formData.tmpurl" mode="aspectFill"></image>
			<view class="mask">
				<view class="icon" @click="editImage">
					<uni-icons type="compose" color="#fff" size="20"></uni-icons>
				</view>
				<view class="icon" @click="delImage">
					<uni-icons type="trash" color="#fff" size="20"></uni-icons>
				</view>
			</view>
		</view>
	</view>

	<cropper-image ref="cropperRef" :maxImgSize="maxImgSize" :tempurl="formData.tmpurl"
		@confirm="cropperChange"></cropper-image>
</template>

<script setup>
	import { ref } from 'vue';

	const cropperRef = ref(null);
	const props = defineProps({
		formData: Object,
		maxImgSize: {
			type: Number,
			default: 3000
		},
		width: {
			type: Number,
			default: 200
		},
		ratio: {
			type: String,
			default: "16 / 9"
		}
	});
	const emits = defineEmits(["update:formData"]);

	//点击选择上传图片
	const selectPicurl = () => {
		uni.chooseImage({
			count: 1,
			success: (res) => {
				emits("update:formData", { ...props.formData, tmpurl: res.tempFilePaths[0] });
			}
		})
	}

	//裁剪完图片
	const cropperChange = (e) => {
		emits("update:formData", { ...props.formData, tmpurl: e })
	}

	//删除图片
	const delImage = () => {
		emits("update:formData", { ...props.formData, tmpurl: "", picurl: "" });
	}

	//编辑图片
	const editImage = () => {
		cropperRef.value.open();
	}
</script>

<style lang="scss" scoped>
	.picGroup {
		.box {
			width: 100px;
			aspect-ratio: 9 / 16;
			border: 1px solid #e4e4e4;
			border-radius: 5px;
			overflow: hidden;
		}

		.add {
			display: flex;
			justify-content: center;
			align-items: center;
			cursor: pointer;
		}

		.pic {
			position: relative;
			background: conic-gradient(#ccc 0 25%, #fff 25% 50%, #ccc 50% 75%, #fff 75%);
			background-size: 10px 10px;

			image {
				width: 100%;
				height: 100%;
			}

			.mask {
				position: absolute;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 30px;
				background: rgba(0, 0, 0, 0.4);
				display: flex;
				justify-content: center;
				align-items: center;

				.icon {
					flex: 1;
					height: 100%;
					display: flex;
					justify-content: center;
					align-items: center;
					cursor: pointer;
				}
			}
		}
	}
</style>